package com.tuanzi.loan.web.bean.settlementsystem;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.starbaba.model.utils.JSONUtils;
import com.tuanzi.loan.business.entity.CurrentUser;
import com.tuanzi.loan.business.entity.settlementsystem.*;
import com.tuanzi.loan.business.entity.system.SystemUser;
import com.tuanzi.loan.business.service.settlementsystem.*;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.settlementsystem.SettlementBillRequest;
import com.tuanzi.loan.vo.response.settlementsystem.SettlementBillResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.settlementsystem.SettlementBillLazyDataModel;
import com.tuanzi.loan.workflow.service.WorkflowManagerService;
import com.tuanzi.loan.workflow.service.WorkflowProcessorService;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.List;
import java.util.Map;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

/**
 * @author caiwanlin
 * @create 2018-08-24 16:32
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class SettlementBillListBean extends JSFListingBean<SettlementBillRequest,SettlementBillResponse> {
    @Autowired
    private SettlementCompanyService settlementCompanyService;

    @Autowired
    private SettlementBillService settlementBillService;

    @Autowired
    private WorkflowManagerService workflowManagerService;

    @Autowired
    private WorkflowProcessorService workflowProcessorService;

    @Autowired
    private SettlementBillAnnexService settlementBillAnnexService;

    private String PROCESS_DEF_KEY = "BillCancel";//作废流程定义key


    private List<SettlementCompany> companyList;

    private SettlementBill settlementBill;

    private List<SettlementIncome> incomeList;

    private List<SettlementPrepay> prepayList;

    private Long billId;
    private String billImageUrl;

    private SettlementBill cancelSettlementBill;//作废记录对象

    private List<SystemUser> checkList;//作废审核人

    private List<SettlementBillAnnex> billAnnexList;//附件

    private String annexUrl;

    @PostConstruct
    public void init() throws Exception {
        companyList = settlementCompanyService.getCompanyList();
        settlementBill = new SettlementBill();
        incomeList = Lists.newArrayList();
        prepayList = Lists.newArrayList();
        checkList = Lists.newArrayList();
        cancelSettlementBill = new SettlementBill();
        billAnnexList = Lists.newArrayList();
        initLazyDataModel();
    }

    private void initLazyDataModel() throws Exception {
        $ = new SettlementBillRequest();
        lazyDataModel = new SettlementBillLazyDataModel($);
    }

    public void onReset(){
        try {
            initLazyDataModel();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onSee(Long id){
        settlementBill = settlementBillService.findOne(id);
        String detailList = settlementBill.getDetailList();
        if (settlementBill.getRecordType() == RemainType.EXPEND.index){//消耗开票
            if (StringUtils.isNotBlank(detailList)){
                incomeList = JSONUtils.fromJsonArrayNew(detailList, SettlementIncome.class);
            }
        }
        else if (settlementBill.getRecordType() == RemainType.PREPAY.index){
            if (StringUtils.isNotBlank(detailList)){
                prepayList = JSONUtils.fromJsonArrayNew(detailList,SettlementPrepay.class);
            }
        }
        billAnnexList = settlementBillAnnexService.findByBillId(id);
        if(billAnnexList == null) billAnnexList = Lists.newArrayList();
        execute("PF('billing').show();");
        update("billForm:bill-info-dialog");

    }

    //查看附件
    public void onSeeAnnex(Integer index){
        SettlementBillAnnex annex = billAnnexList.get(index);
        annexUrl = annex.getUrl();
        update("billForm:annex-image");
    }

    public void onCancel(Long id){
        cancelSettlementBill = settlementBillService.findOne(id);
        if (!CurrentUser.get().getName().equals(cancelSettlementBill.getCreator())){
            addErrorMessage("此记录不是您创建，无法作废");
            return;
        }
        checkList = workflowManagerService.findFirstActivitySystemUserProcDefKey(PROCESS_DEF_KEY);
        execute("PF('billCancel').show()");
        update("billForm:bill-cancel-dialog");
    }

    public void onSubmitCancel(){
        if (StringUtils.isBlank(cancelSettlementBill.getCancelAccount())){
            addErrorMessage("请选择作废审核人");
            return;
        }

        //保存
        String checkName = checkList.parallelStream().filter(s -> s.getAccount().equals(cancelSettlementBill.getCancelAccount()))
                .map(s -> s.getName()).findFirst().get();
        cancelSettlementBill.setCancelName(checkName);//审核人姓名
        cancelSettlementBill.setBillStatus(BillStatus.OBSOLETE_CHECK.index);
        settlementBillService.saveOrUpdate(cancelSettlementBill);


        //启动流程
        String account = CurrentUser.get().getAccount();
        String assignee = cancelSettlementBill.getCancelAccount();
        String title = "【作废】流程【"+cancelSettlementBill.getCompanyName()+"】";
        List<String> businessKeys = Lists.newArrayList(cancelSettlementBill.getId().toString());
        Map<String, Object> variables = Maps.newHashMap();
        workflowProcessorService.startProcess(account,assignee,PROCESS_DEF_KEY,title,businessKeys,variables);
        addSuccessfullyMessage();
        execute("PF('billCancel').hide()");
        update("billForm");

    }


    public void handleBillImageUpload(FileUploadEvent event){
        UploadedFile file = event.getFile();
        String url = this.uploadImg(file);
        SettlementBill one = settlementBillService.findOne(billId);
        one.setBillImageUrl(url);
        settlementBillService.saveOrUpdate(one);
        addInfoMessage("上传成功");
        execute("PF('billImage').hide();");
        update("billForm");
    }

    @Override
    protected List<String> getDictionaryCodes() {
        return  Lists.newArrayList(SETTLEMENT_SPREAD_CHANNEL,SETTLEMENT_INCOME_TYPE,
                SETTLEMENT_SPREAD_MODE, COOPERATION_MODE, SETTLEMENT_CYCLE,
                SETTLEMENT_BILLING_CONTENT,SETTLEMENT_BILL_TYPE,SETTLEMENT_PAY_MODE,SETTLEMENT_RECEIVE_COMPANY,SETTLEMENT_BILL_STATUS);
    }
}
